package com.axa.mule.transformer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.hibernate.TransactionException;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.config.i18n.MessageFactory;
import org.mule.transformer.AbstractMessageTransformer;

import com.axa.sms.portal.Stringlist;

public class HSSFReportTransformer extends AbstractMessageTransformer {
	private static Logger logger = Logger.getLogger(HSSFReportTransformer.class);
	private static final String eol = System.getProperty("line.separator");
	
	@Override
	public Object transformMessage(MuleMessage message, String outputEncoding)
			throws TransformerException {
		
		/*
		*	open Payload(i.e. FileStream) as HSSF-stream
		*/
		Workbook wb = null;
		try {
			wb = new HSSFWorkbook((ByteArrayInputStream) message.getPayload());
		} catch (IOException e) {
			logger.error(e.getMessage(), e.getCause());
			throw new TransformerException(this, e.getCause());
		}
		
		Sheet sheet = wb.getSheetAt(wb.getActiveSheetIndex());
		
		Integer messages = sheet.getPhysicalNumberOfRows();
		if (messages == 0) {
			logger.trace("no rows to proceed");
			message.setInvocationProperty("report", "There's no SMS to proceed!");
			return message;
		}
		
		Stringlist list = message.getInvocationProperty("ws.response");

		/* filling HSSF with WS/SOAP reply */
		Integer warns = 0;
		for (int i = 0; i < messages; i++) {
			String reply = ""; 
			try {
				reply = list.getStr().get(i);
			} catch (Exception e) {
				logger.error(""+ this.getClass() +"wrong WS response. "+ e.getMessage());
				throw new TransformerException(MessageFactory.createStaticMessage("wrong response "+ e.getMessage()), this);
			}
			
			if (reply.contains("WARN:")){
				warns++;

				int columns = sheet.getRow(i).getLastCellNum();

				Row row = sheet.getRow(i);
				Cell cell = row.getCell(columns+1);
				if (cell == null)
					cell = row.createCell(columns+1);
				cell.setCellType(Cell.CELL_TYPE_STRING);
				cell.setCellValue(reply);
			}
		}
		
		
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			wb.write(out);
		} catch (IOException e) {
			throw new TransactionException("error while writing stream"+ e.getMessage());
		}
		message.setPayload(out.toByteArray());
		

		/* email body */
		String msgbody = "QUICK REPORT";
		msgbody += eol  +"total messages: "+ messages.toString();
		if (warns > 0)
			msgbody += eol + "error msg: "+ warns;
		msgbody += eol + "successful: "+ (messages - warns);
		message.setInvocationProperty("report", msgbody);
		
		return (message);
	}

}
